﻿using System;
using Microsoft.Xna.Framework.Graphics;

namespace Deferred.Library
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class GraphicalComponent
    {
        /// <summary>
        /// 
        /// </summary>
        protected IGraphicsDeviceService graphicsService { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        protected virtual bool LoadContentUponCreation { get { return true; } }

        /// <summary>
        /// 
        /// </summary>
        protected GraphicsDevice GraphicsDevice { get { return graphicsService.GraphicsDevice; } }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="graphicsService"></param>
        public GraphicalComponent(IGraphicsDeviceService graphicsService)
        {
            this.graphicsService = graphicsService;

            setupHooks();

            if (GraphicsDevice != null && LoadContentUponCreation) LoadContent();
        }

        private void setupHooks()
        {
            graphicsService.DeviceCreated += new EventHandler(graphicsService_NewDevice);
            graphicsService.DeviceResetting += new EventHandler(graphicsService_DestroyingDevice);
            graphicsService.DeviceReset += new EventHandler(graphicsService_NewDevice);
            graphicsService.DeviceDisposing += new EventHandler(graphicsService_DestroyingDevice);
        }

        private void graphicsService_DestroyingDevice(object sender, EventArgs e)
        {
            DestroyContent();
        }

        private void graphicsService_NewDevice(object sender, EventArgs e)
        {
            LoadContent();
        }

        /// <summary>
        /// 
        /// </summary>
        protected virtual void DestroyContent() { }

        /// <summary>
        /// 
        /// </summary>
        protected virtual void LoadContent() { }
    }
}
